package com.ueboot.weishop.api.controller.order;

import com.ueboot.core.exception.BusinessException;
import com.ueboot.core.http.response.Response;
import com.ueboot.weishop.api.SessionUtils;
import com.ueboot.weishop.api.controller.order.vo.*;
import com.ueboot.weishop.entity.customer.CustomerInfoEntity;
import com.ueboot.weishop.entity.customer.CustomerInvoiceEntity;
import com.ueboot.weishop.entity.customer.CustomerReceiverEntity;
import com.ueboot.weishop.entity.order.*;
import com.ueboot.weishop.service.customer.CustomerInvoiceService;
import com.ueboot.weishop.service.customer.CustomerReceiverService;
import com.ueboot.weishop.service.customer.CustomerService;
import com.ueboot.weishop.service.order.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ueboot.weishop.entity.order.OrderEnum.*;

/**
 * Created by zl  on 2017-11-05 12:39:14.
 * 订单接口
 * - 查询订单
 * - 分页查询订单
 *
 * @author zl
 * @since 2.0 by autocode
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/private/my/order")
public class MyOrderController {

    @Autowired
    private OrderService service;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderInvoiceService orderInvoiceService;

    @Autowired
    private OrderReceiverService orderReceiverService;

    @Autowired
    private OrderIssueService issueService;

    @Autowired
    private CustomerInvoiceService customerInvoiceService;

    @Autowired
    private CustomerReceiverService customerReceiverService;

    @Autowired
    private OrderExtensionService orderExtensionService;

    /**
     * 查询订单
     **/
    @RequestMapping(value = "/lists", method = RequestMethod.POST)
    public Response<List<MyOrderResp>> list() {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        CustomerInfoEntity customerInfoEntity = customerService.findByOpenId(com.ueboot.weishop.api.SessionUtils.getOpenId());
        if (customerInfoEntity == null) {
            throw new BusinessException("会员信息不存在");
        }

        List<OrderEntity> entities = service.findByCustomerId(customerInfoEntity.getId());
        List<MyOrderResp> body = new ArrayList<>();
        for (OrderEntity entity : entities) {
            MyOrderResp resp = new MyOrderResp();
            BeanUtils.copyProperties(entity, resp);

            if (orderInvoiceService.findByOrderOrderNo(entity.getOrderNo()) != null) {
                resp.setInvoice("是");
            } else {
                resp.setInvoice("否");
            }
            resp.setPayAmount(resp.getPayAmount() / 100);
            body.add(resp);
        }
        return new Response<>(body);
    }


    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public Response<MyOrderGetResp> get(@RequestBody MyOrderGetReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        OrderEntity order = service.findByOrderNo(req.getOrderNo());
        MyOrderGetResp resp = new MyOrderGetResp();
        BeanUtils.copyProperties(order, resp);
        resp.setPayAmount(resp.getPayAmount() / 100);
        return new Response<>(resp);
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Response<Page<MyOrderResp>> pageByCustomerId(@RequestBody(required = false) MyOrderReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        CustomerInfoEntity customerInfoEntity = customerService.findByOpenId(com.ueboot.weishop.api.SessionUtils.getOpenId());
        if (customerInfoEntity == null) {
            throw new BusinessException("会员信息不存在");
        }

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(req.getPageNumber(), req.getPageSize(), sort);
        Page<OrderEntity> entities = null;
        //已支付
        if (req.getType().equals(ORDER_STATUS_2)) {
            entities = service.findByCustomerIdAndOrderStatusAndRefundStatus(pageable, customerInfoEntity.getId(), ORDER_STATUS_2, REFUND_STATUS_0);
        }//未支付
        else if (req.getType().equals(ORDER_STATUS_0)) {
            entities = service.findByCustomerIdAndOrderStatusAndRefundStatus(pageable, customerInfoEntity.getId(), ORDER_STATUS_0, REFUND_STATUS_0);
        }//退款单
        else if (req.getType().equals(REFUND_NAME_0)) {
            entities = service.findByCustomerIdAndRefundStatusNot(pageable, customerInfoEntity.getId(), REFUND_STATUS_0);
        }//全部
        else {
            entities = service.findByCustomerId(pageable, customerInfoEntity.getId());
        }

        Page<MyOrderResp> body = entities.map(entity -> {
            MyOrderResp resp = new MyOrderResp();
            BeanUtils.copyProperties(entity, resp);
            if (orderInvoiceService.findByOrderOrderNo(entity.getOrderNo()) != null) {
                resp.setInvoice("是");
            } else {
                resp.setInvoice("否");
            }
            resp.setPayAmount(resp.getPayAmount() / 100);
            resp.setRefund(true);
            if (entity.getApplyRefundValidTime() != null) {
                resp.setRefund(new Date().after(entity.getApplyRefundValidTime()));
            }
            if ("102,103,104".contains(resp.getCategoryCode())) {
                resp.setRefund(false);
            }
            resp.setGoodsName(entity.getGoodsName());
            return resp;
        });

        return new Response<>(body);
    }


    @RequestMapping(value = "/crowd/page", method = RequestMethod.POST)
    public Response<Page<OrderCrowdResp>> crowdPage(@RequestBody(required = false) MyOrderReq req) {
        String categoryCode = "102";
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(req.getPageNumber(), req.getPageSize(), sort);
        Page<OrderExtensionEntity> entities = null;
        //进行中
        if ("进行中".equalsIgnoreCase(req.getType())) {
            entities = orderExtensionService.findByCustomerOpenIdAndLotteryAndCategoryCode(pageable, openId, categoryCode, OrderExtensionEntity.LOTTERY_UN);
        }//已揭晓
        else if ("已揭晓".equalsIgnoreCase(req.getType())) {
            entities = orderExtensionService.findByCustomerOpenIdAndCategoryCodeAndLotteryNot(pageable, openId, categoryCode, OrderExtensionEntity.LOTTERY_UN);
        }//全部
        else {
            entities = orderExtensionService.findByCustomerOpenIdAndCategoryCode(pageable, openId, categoryCode);
        }

        Page<OrderCrowdResp> body = entities.map(entity -> {
            OrderCrowdResp resp = new OrderCrowdResp();
            BeanUtils.copyProperties(entity, resp);
            resp.setCopies(StringUtils.isNotEmpty(entity.getLotteryNums()) ? entity.getLotteryNums().split(",").length : 0);
            resp.setGoodsName(entity.getGoodsName());
            resp.setPeriodNum(entity.getPeriodNum());
            resp.setLotteryNums(entity.getLotteryNums());
            resp.setLottery(entity.getLottery());
            resp.setLotteryNum(entity.getLotteryNum());
            return resp;
        });

        return new Response<>(body);
    }


    /**
     * 完善订单信息
     **/
    @RequestMapping(value = "/invoice/receiver/save", method = RequestMethod.POST)
    public Response<Void> saveReceiver(@RequestBody PerfectReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        OrderEntity orderEntity = service.findByOrderNo(req.getOrderNo());

        CustomerInvoiceEntity customerInvoiceEntity = customerInvoiceService.get(req.getInvoiceId());

        OrderInvoiceEntity orderInvoice = orderInvoiceService.findByOrderOrderNo(req.getOrderNo());
        if (orderInvoice == null) {
            orderInvoice = new OrderInvoiceEntity();
        }
        orderInvoice.setTaxFileNumber(customerInvoiceEntity.getTaxFileNumber());
        orderInvoice.setTitleName(customerInvoiceEntity.getTitleName());
        orderInvoice.setInvoiceType(customerInvoiceEntity.getInvoiceType());
        orderInvoice.setCustomer(customerInvoiceEntity.getCustomer());
        orderInvoice.setOrder(orderEntity);
        orderInvoiceService.save(orderInvoice);

        CustomerReceiverEntity customerReceiverEntity = customerReceiverService.get(req.getReceiverId());

        OrderReceiverEntity orderReceiver = orderReceiverService.findByOrderOrderNo(req.getOrderNo());
        if (orderReceiver == null) {
            orderReceiver = new OrderReceiverEntity();
        }
        orderReceiver.setProvinceName(customerReceiverEntity.getProvinceName());
        orderReceiver.setCityName(customerReceiverEntity.getCityName());
        orderReceiver.setAreaName(customerReceiverEntity.getAreaName());
        orderReceiver.setAddress(customerReceiverEntity.getAddress());
        orderReceiver.setConsignee(customerReceiverEntity.getConsignee());
        orderReceiver.setMobile(customerReceiverEntity.getMobile());
        orderReceiver.setCustomer(customerReceiverEntity.getCustomer());
        orderReceiver.setOrder(orderEntity);
        orderReceiverService.save(orderReceiver);
        return new Response<>();
    }

    /**
     * 查询订单明细
     **/
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public Response<MyOrderDetailResp> orderDetail(@RequestBody MyOrderDetailReq req) {

        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }

        MyOrderDetailResp resp = new MyOrderDetailResp();

        OrderEntity orderEntity = service.findByOrderNo(req.getOrderNo());
        OrderInvoiceEntity orderInvoiceEntity = orderInvoiceService.findByOrderOrderNo(req.getOrderNo());
        OrderReceiverEntity orderReceiverEntity = orderReceiverService.findByOrderOrderNo(req.getOrderNo());
        OrderExtensionEntity orderExtensionEntity = orderExtensionService.findByOrderNo(req.getOrderNo());
        BeanUtils.copyProperties(orderEntity, resp);
        if(orderExtensionEntity.getLotteryNums()!=null){
            resp.setLotteryNumbers(orderExtensionEntity.getLotteryNums());
        }
        if(orderExtensionEntity.getLotteryNum()!=null){
            resp.setLotteryNumber(orderExtensionEntity.getLotteryNum());
        }
        resp.setTitleName(orderInvoiceEntity == null ? null : orderInvoiceEntity.getTitleName());
        resp.setTaxFileNumber(orderInvoiceEntity == null ? null : orderInvoiceEntity.getTaxFileNumber());
        resp.setAddress(orderReceiverEntity == null ? null : orderReceiverEntity.getProvinceName() + orderReceiverEntity.getCityName() + orderReceiverEntity.getAreaName() + orderReceiverEntity.getAddress());
        resp.setCustomerVin(orderExtensionEntity == null ? null : orderExtensionEntity.getCustomerVin());
        resp.setCarType(orderExtensionEntity == null ? null : orderExtensionEntity.getCarType());
        resp.setTargetDealer(orderExtensionEntity == null ? null : orderExtensionEntity.getTargetDealer());
        resp.setPayAmount(resp.getPayAmount() / 100);
        resp.setRefund(true);
        if (orderEntity.getApplyRefundValidTime() != null) {
            resp.setRefund(new Date().after(orderEntity.getApplyRefundValidTime()));
        }
        if ("102,103,104".contains(resp.getCategoryCode())) {
            resp.setRefund(false);
        }
        return new Response<>(resp);
    }


    @RequestMapping(value = "receiver/save", method = RequestMethod.POST)
    public Response<Void> save(@RequestBody OrderReceiverReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        CustomerInfoEntity customerInfoEntity = customerService.findByOpenId(com.ueboot.weishop.api.SessionUtils.getOpenId());
        OrderReceiverEntity entity = null;
        if (req.getId() == null) {
            entity = new OrderReceiverEntity();
        } else {
            entity = orderReceiverService.get(req.getId());
        }
        BeanUtils.copyProperties(req, entity);
        entity.setCustomer(customerInfoEntity);
        orderReceiverService.save(entity);
        return new Response<>();
    }

    @RequestMapping(value = "invoice/save", method = RequestMethod.POST)
    public Response<Void> save(@RequestBody OrderInvoiceReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        CustomerInfoEntity customerInfoEntity = customerService.findByOpenId(com.ueboot.weishop.api.SessionUtils.getOpenId());
        OrderInvoiceEntity entity = null;
        if (req.getId() == null) {
            entity = new OrderInvoiceEntity();
        } else {
            entity = orderInvoiceService.get(req.getId());
        }
        BeanUtils.copyProperties(req, entity);
        entity.setCustomer(customerInfoEntity);
        orderInvoiceService.save(entity);
        return new Response<>();
    }

    @RequestMapping(value = "/refund", method = RequestMethod.POST)
    public Response<Void> refund(@RequestBody OrderRefundReq req) {
        String openId = SessionUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            throw new BusinessException("请使用微信！");
        }
        // 根据orderNo查询发送DMS的组装数据 OrderIssueEntity，像DMS发起退货申请请求。将反馈结果保存，
        // 若可退款，手动后台退款，
        // 若不可退款，将反馈不能退款结果更新至order并更新订单退款状态。
        OrderEntity order = service.findByOrderNo(req.getOrderNo());
        if (!REFUND_STATUS_0.equals(order.getRefundStatus())) {
            throw new BusinessException("00", "退款状态为：" + order.getRefundStatus() + "不能申请退款");
        } else if (order.getApplyRefundValidTime() == null || new Date().after(order.getApplyRefundValidTime())) {
            throw new BusinessException("01", "退款时效已过，不能提交申请");
        }
        order.setRefundStatus(OrderEnum.REFUND_STATUS_1);//默认设置为待审核，若DMS验证后已使用将其改成退款失败，并更新退款结果为DMS反馈结果。
        order.setRefundReason(req.getReason());
        this.service.update(order);
        return new Response<>();
    }
}
